﻿<template>
  <header style="font-size: xx-large;">自定义开发环境！</header>
  <h1>
      ①开发环境信息
      <h6>开发环境名称</h6>
      <el-input
          v-model="ideName"
          style="width: 240px"
          :rows="1"
          type="textarea"
          placeholder="请输入IDE的名称"
      />
      <h6>开发环境描述</h6>
      <el-input
          v-model="ideDescription"
          style="width: 360px"
          :rows="3"
          type="textarea"
          placeholder="简单描述一下这个IDE"
      />
      <h6>基本应用模板</h6>
      <h6 style="color: grey;">待添加...</h6>
  </h1>
  <h1>软件包</h1>
  <el-tree
      class="tree-container"
      :props="props"
      :data="Softwares"
      node-key="label"
      show-checkbox
      style="height: 208px;"
      default-expand-all
      ref="softwareTreeRef" ></el-tree>
  <h1>插件</h1>
  <el-tree
      class="tree-container"
      :props="props"
      :data="Plugins"
      node-key="label"
      show-checkbox
      style="height: 208px;"
      default-expand-all
      ref="pluginTreeRef"
  />
  <el-button @click="createTemplate">生成开发环境</el-button> <!-- 修改按钮的调用方法 -->
</template>

<script setup lang="ts" name="Customize">
import axios from 'axios';
import { ref, onMounted, watch } from 'vue';
import { ElTree, ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { v4 as uuidv4 } from 'uuid';

interface Tree {
  label: string;
  children?: Tree[];
}

const props = {
  label: 'label',
  children: 'children',
  isLeaf: 'leaf',
};


const ideName = ref('');
const ideDescription = ref('');
const Softwares = ref<Tree[]>([]);
const Plugins = ref<Tree[]>([]);
const selectedSoftwares = ref<string[]>([]); 
const selectedPlugins = ref<string[]>([]);
const softwareTreeRef = ref<InstanceType<typeof ElTree>>();
const pluginTreeRef = ref<InstanceType<typeof ElTree>>();
const authToken = localStorage.getItem('authToken');
const route = useRoute(); 

// 获取或生成 UUID
// let pageKey = localStorage.getItem('current-page-uuid');
// if (!pageKey) {
//   pageKey = uuidv4(); // 生成新的 UUID
//   localStorage.setItem('current-page-uuid', pageKey); // 存储 UUID
// } else {
//   pageKey = String(pageKey); // 确保 pageKey 是字符串类型
// }

// // 保存到 localStorage，使用 UUID 作为键名
// const saveCheckedKeysToLocalStorage = () => {
//   const checkedSoftwares = softwareTreeRef.value?.getCheckedKeys(false) || [];
//   const checkedPlugins = pluginTreeRef.value?.getCheckedKeys(false) || [];
  
//   const pageData = {
//     ideName: ideName.value,
//     ideDescription: ideDescription.value,
//     selectedSoftwares: checkedSoftwares,
//     selectedPlugins: checkedPlugins,
//   };
//   console.log(pageData);
//   localStorage.setItem(pageKey, JSON.stringify(pageData)); // 使用 UUID 存储页面数据
// };

// // 从 localStorage 恢复数据
// const restoreCheckedKeysFromLocalStorage = () => {
//   const savedData = JSON.parse(localStorage.getItem(pageKey));
//   console.log(pageKey);
//   if (savedData) {
//     ideName.value = savedData.ideName;
//     ideDescription.value = savedData.ideDescription;
//     selectedSoftwares.value = savedData.selectedSoftwares || [];
//     selectedPlugins.value = savedData.selectedPlugins || [];
    
//     // 恢复树形组件的勾选状态
//     if (softwareTreeRef.value) {
//       softwareTreeRef.value.setCheckedKeys(selectedSoftwares.value);
//     }
//     if (pluginTreeRef.value) {
//       pluginTreeRef.value.setCheckedKeys(selectedPlugins.value);
//     }
//   }
// };

const fetchPluginData = async () => {
  try {
      const response = await axios.get<Tree[]>(`${window.location.protocol}//${window.location.hostname}/api/plugin-data`);
      Plugins.value = response.data;
  } catch (error) {
      console.error('Failed to fetch plugin data:', error);
  }
};

const fetchSoftwareData = async () => {
  try {
      const response = await axios.get<Tree[]>(`${window.location.protocol}//${window.location.hostname}/api/software-data`);
      Softwares.value = response.data;
  } catch (error) {
      console.error('Failed to fetch software data:', error);
  }
};

const fetchEnvironmentData = async (name: string) => {
  try {
      const response = await axios.get(`${window.location.protocol}//${window.location.hostname}/api/environment?name=${name}`);
      
      const { Softwares: fetchedSoftwares, Plugins: fetchedPlugins } = response.data; 
  
      // 更新选中的软件和插件
      selectedSoftwares.value = fetchedSoftwares;
      selectedPlugins.value = fetchedPlugins;
      console.log(selectedSoftwares);
      console.log(selectedPlugins);
      if (softwareTreeRef.value) {
          softwareTreeRef.value.setCheckedKeys(selectedSoftwares.value);
      }
      if (pluginTreeRef.value) {
          pluginTreeRef.value.setCheckedKeys(selectedPlugins.value);
      }
      console.log(pluginTreeRef.value);
      console.log(softwareTreeRef.value);
  } catch (error) {
      console.error('Failed to fetch environment data:', error);
  }
};
const createTemplate = async () => {
  if (!ideName.value.trim()) {
      ElMessage.error('IDE名称不能为空');
      return;
  }

  if (!ideDescription.value.trim()) {
      ElMessage.error('IDE描述不能为空');
      return;
  }

  const Softwares = softwareTreeRef.value?.getCheckedKeys(false) || [];
  const Plugins = pluginTreeRef.value?.getCheckedKeys(false) || [];
  
  try {
      await axios.post(
        `${window.location.protocol}//${window.location.hostname}/api/create-template`, 
        {
          ideName: ideName.value,
          ideDescription: ideDescription.value,
          softwares: Softwares,
          plugins: Plugins,
        },
        {
          headers: { 'Authorization': `Token ${authToken}` }  // 将token正确地放在headers中
        }
      );
      ElMessage.success('开发环境生成成功！');
  } catch (error) {
      console.error('Error creating template:', error);
      ElMessage.error('生成开发环境失败！');
  }
};

onMounted(() => {
  fetchPluginData();
  fetchSoftwareData();
  
  const name = route.query.name;
  if (name) {
      // 如果有 query 参数，则从远程获取选中的选项
      fetchEnvironmentData(String(name));
  } else {
      // 如果没有 query 参数，则从 localStorage 恢复
      //console.log('restore');
      //restoreCheckedKeysFromLocalStorage();
  }
});

// 监听树节点的变化，保存选中的项到 localStorage
//watch([softwareTreeRef.value, pluginTreeRef.value], saveCheckedKeysToLocalStorage);
</script>

<style scoped>
.colorboard1 {
  background-color: rgb(50, 50, 64);
  color: white;
  font-family: '等线';
}

.tree-container {
  height: 300px; /* 设置固定高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
  margin-bottom: 20px; /* 添加底部间距 */
  border-radius: 4px;
}
</style>
